package com.sy.cloud.wechat.utils;

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * Created by mac on 2017-10-30.
 */
public class WeChatUtils {
    private WeChatUtils() {
    }

    public static boolean checkSignature(String token, String timestamp, String nonce, String signature) throws NoSuchAlgorithmException {
        String[] arr = new String[]{token, timestamp, nonce};
        StringBuffer sb = new StringBuffer();
        Arrays.sort(arr);

        for(int i = 0; i < arr.length; ++i) {
            sb.append(arr[i]);
        }

        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(sb.toString().getBytes());
        byte[] digest = md.digest();
        StringBuffer hexstr = new StringBuffer();
        String shaHex = "";

        for(int i = 0; i < digest.length; ++i) {
            shaHex = Integer.toHexString(digest[i] & 255);
            if (shaHex.length() < 2) {
                hexstr.append(0);
            }

            hexstr.append(shaHex);
        }

        return hexstr != null ? hexstr.toString().equals(signature) : false;
    }

    public static String readResourceJsonFile(String path) throws IOException {
        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
        return IOUtils.toString(inputStream);
    }
}
